<template>
  <div>
    <!-- 头像 -->
    <div class="user-avatar">
      <!-- <img :src="getImageUrl('avatar/' + user.user_avatar)" alt=""> -->
      <el-avatar :size="200" fit="cover" :src="getImageUrl('avatar/' + user.user_avatar)" />
    </div>
    <!-- 菜单栏 -->
    <div class="center-items">
      <el-row :gutter="21">
        <el-col :span="7">
          <div class="grid-content" @click="dialogUserVisible = true">个人信息</div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content" @click="dialogStudyVisible = true">已学算法</div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content" @click="dialogCollectVisible = true">收藏题集</div>
        </el-col>
      </el-row>
      <el-row :gutter="21">
        <el-col :span="7">
          <div class="grid-content" @click="dialogCommentVisible = true">我的评论</div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content" @click="dialogLikeVisible = true">我的消息</div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content" @click="dialogLogoutVisible = true">注销账号</div>
        </el-col>
      </el-row>
    </div>
    <!-- 我的信息 -->
    <el-dialog class="user-info" v-model="dialogUserVisible" title="个人信息" width="600" center align-center>
      <div class="info-item">
        <div class="icon">
          <img src="../../icons/user.svg" alt="">
        </div>
        这位同学是：{{ user.user_name }}
      </div>
      <div class="info-item">
        <div class="icon">
          <img src="../../icons/date.svg" alt="">
        </div>
        首次学习于：{{ user.join_time }}
      </div>
      <div class="info-item">
        <div class="icon">
          <img src="../../icons/email.svg" alt="">
        </div>
        邮箱是：{{ user.email }}
      </div>
      <div class="info-item">
        <div class="icon">
          <img src="../../icons/exercise.svg" alt="">
        </div>
        已刷题数：{{ user.correct_num + user.wrong_num
        }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        正确率：{{ yes != NaN ? yes : 0 }}%
      </div>
      <div class="info-item">
        <div class="icon">
          <img src="../../icons/motto.svg" alt="">
        </div>
        {{ user.motto }}
      </div>
      <template #footer>
        <el-button type="primary" @click="openDialog">修改信息</el-button>
      </template>
      <!-- 修改信息表单 -->
      <el-dialog v-model="changeinfoVisible" width="500" title="修改用户信息" append-to-body align-center>
        <el-form ref="updateFormRef" :model="updateForm" :rules="rules" label-width="80px" class="demo-ruleForm"
          status-icon>
          <el-form-item label="头像:">
            <el-upload class="avatar-uploader" action="/oasadapi/users/upload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="!imgFlag" :src="getImageUrl('avatar/' + imageUrl)" class="avatar" />
              <img v-else :src="imageUrl" class="avatar" />
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名:" prop="user_name">
            <el-input v-model="updateForm.user_name" disabled />
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input v-model="updateForm.password" type="password" show-password />
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="updateForm.email" />
          </el-form-item>
          <el-form-item label="签名:" prop="motto">
            <el-input v-model="updateForm.motto" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="changeinfoVisible = false">取消</el-button>
            <el-button type="primary" @click="handleUpdateConfirm">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>

    <!-- 已学算法 -->
    <el-dialog class="studied" v-model="dialogStudyVisible" title="已学算法" width="600" center align-center>
      <el-empty v-if="!haveStudy" description="还没有学习过，快去开启旅途吧！" />
      <div v-else class="study">
        <span class="study-items" v-for="(item, index) in studiedAlgList" :key="index">
          <el-tag :type="tagList[index % 5]" @click="goStudy(item.alg_url)">{{ item.alg_name }}</el-tag>
        </span>
      </div>
    </el-dialog>

    <!-- 收藏题集 -->
    <el-dialog class="collection" v-model="dialogCollectVisible" title="收藏题集" width="600" center align-center>
      <el-empty v-if="!haveConllect" description="还没有收藏过，是大侠还是懒虫呢？" />
      <div v-else>
        <div>收藏题数：{{ collectionList.length }}</div>
        <el-scrollbar height="420px">
          <el-collapse :v-model="0" accordion>
            <div v-for="(item, index) in collectionList" :key="item.id">
              <el-collapse-item class="notice" :title="index + 1 + item.exercise.content" :name="item.id">
                <div v-if="item.exercise.pic !== null" class="pic">
                  <img :src="getImageUrl(item.exercise.pic)" alt="">
                </div>
                <div>{{ item.exercise.answer_a }}</div>
                <div>{{ item.exercise.answer_b }}</div>
                <div>{{ item.exercise.answer_c }}</div>
                <div>{{ item.exercise.answer_d }}</div>
                <div>答案：{{ item.exercise.answer }}
                  <span><el-button class="withdraw" type="info" plain size="small"
                      @click="cancel(item.id)">取消收藏</el-button></span>
                </div>
              </el-collapse-item>
            </div>
          </el-collapse>
        </el-scrollbar>
      </div>
    </el-dialog>

    <!-- 我的评论 -->
    <el-dialog class="commented" v-model="dialogCommentVisible" title="我的评论" width="600" center align-center>
      <el-empty v-if="!haveComment" description="还没有评论过，快去留下足迹吧！" />
      <div v-else>
        <div class="comment-top">
          <div>发布评论：{{ commentList.length }}条</div>
        </div>
        <el-scrollbar height="400px">
          <div class="comment-card" v-for="item, index in commentList" :key="index">
            <div class="avatar">
              <el-avatar :size="55" fit="cover" :src="getImageUrl('avatar/' + item.avatar)" />
            </div>
            <div class="comment-rigth">
              <div class="userName">
                {{ item.author }}
              </div>
              <div class="comment-text">
                {{ item.comment }}
              </div>
              <div class="comment-time">
                发布于：{{ item.publish_time }}
              </div>
            </div>
            <el-popconfirm title="您确定要撤回该评论吗?" @confirm="handleApproval(item, 2)">
              <template #reference>
                <el-button class="withdraw" type="info" plain size="small">撤回评论</el-button>
              </template>
            </el-popconfirm>
          </div>
        </el-scrollbar>
      </div>
    </el-dialog>

    <!-- 我的消息 -->
    <el-dialog class="liked" v-model="dialogLikeVisible" title="我的消息" width="600" center align-center>
      <el-empty v-if="!haveLike" description="收信箱空空如也..." />
      <div v-else>
        <el-badge :value="notRead" class="item">
          <el-tag type="info">未读</el-tag>
        </el-badge>
        <el-scrollbar height="410px">
          <el-collapse v-model="activeNames" accordion>
            <div v-for="item in noticeList" :key="item.id">
              <el-collapse-item v-if="item.status === 0" class="notice" :title="item.post_from + '给你发来了一条消息(未读)'"
                :name="item.id" @click="handleChangeStatus(item)">
                <div>{{ item.notice }}</div>
                <div>{{ "发送于：" + item.post_time }}</div>
              </el-collapse-item>
              <el-collapse-item v-else class="notice" :title="item.post_from + '给你发来了一条消息(已读)'" :name="item.id"
                @click="handleChangeStatus(item)">
                <div>{{ item.notice }}</div>
                <div>{{ "发送于：" + item.post_time }}</div>
              </el-collapse-item>
            </div>
          </el-collapse>
        </el-scrollbar>
      </div>
    </el-dialog>

    <!-- 注销账号 -->
    <el-dialog class="logout" v-model="dialogLogoutVisible" title="注销账号" width="600" center align-center>
      <span class="logout-text">确定注销账号吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogLogoutVisible = false">取消</el-button>
          <el-button type="danger" @click="handleLogout(user.id)">
            注销
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { useUserStore } from "../../store/useUserStore.js";
import { useRouterStore } from "../../store/useRouterStore.js";
// import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

// 初始化
onMounted(() => {
  // 获取user信息
  changeUserInfo().then(() => {
    if (user.value.correct_num === 0 && user.value.wrong_num === 0) { yes.value = 0 } else
      yes.value = (user.value.correct_num / (user.value.correct_num + user.value.wrong_num) * 100).toFixed(2);
    // 获取消息列表
    getNoticeList(user.value.user_name);
    // 获取已学算法列表
    getStuduedAlgList(user.value.user_name);
  });
  // 获取评论列表
  getCommentList();
  // 获取收藏列表
  getCollectinList();
})

// 定义弹出框显示变量
let dialogUserVisible = ref(false);
let dialogStudyVisible = ref(false);
let dialogCollectVisible = ref(false);
let dialogCommentVisible = ref(false);
let dialogLikeVisible = ref(false);
let dialogLogoutVisible = ref(false);
let changeinfoVisible = ref(false);
// 个人信息
const userStore = useUserStore();
const { user } = storeToRefs(userStore);
let yes = ref((user.value.correct_num / (user.value.correct_num + user.value.wrong_num) * 100).toFixed(2));

// 弹出修改个人信息框
const openDialog = () => {
  changeinfoVisible.value = true;
  imgFlag.value = 0;
  imageUrl.value = user.value.user_avatar;
  updateForm.user_avatar = user.value.user_avatar;
  updateForm.user_name = user.value.user_name;
  updateForm.password = user.value.password;
  updateForm.email = user.value.email;
  updateForm.motto = user.value.motto;
}
// 更新表单
const updateFormRef = ref()
const updateForm = reactive({
  user_avatar: "",
  user_name: "",
  password: "",
  email: "",
  motto: "",
  committer: "",
  committer_id: "",
})
const rules = reactive({
  user_name: [
    { message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { message: '请输入密码', trigger: 'blur' },
  ],
  email: [
    { message: '请输入邮箱', trigger: 'blur' },
  ],
  motto: [
    { message: '请输入签名', trigger: 'blur' },
  ],
})
// 上传图片
const imgFlag = ref(0);
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log(response);
  updateForm.user_avatar = uploadFile.name;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  imgFlag.value = 1;
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像图片必须是JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('头像图片大小不能超过5MB!')
    return false
  }
  return true
}

// 更新公共状态user
const changeUserInfo = async () => {
  const res = await axios.post(`/oasadapi/users/${user.value.id}`);
  let { data } = res.data;
  userStore.changeUser(data)
}

const handleUpdateConfirm = async () => {
  changeinfoVisible.value = false;
  updateForm.committer = user.value.user_name;
  updateForm.committer_id = user.value.id;
  if (updateForm.user_avatar === user.value.avatar && updateForm.password === user.value.password && updateForm.motto === user.value.motto && updateForm.email === user.value.email) {
    ElMessage({
      message: "请修改信息后再提交哦！",
      type: "warning"
    })
  } else
    await axios.post(`/oasadapi/users/postupdateinfo`, updateForm).then((res) => {
      if (res.data.code === 0) {
        ElMessage({
          message: "提交成功，管理员审核中...",
          type: "success"
        })
      } else {
        ElMessage({
          message: "提交失败，请检查网络！",
          type: "error"
        })
      }
    });
}

// 已学算法
let haveStudy = ref(false);
const router = useRouter();
const studiedAlgList = ref([]);
const goStudy = (path: string) => {
  router.push(path);
}
const getStuduedAlgList = async (user_name: string) => {
  await axios.get(`/oasadapi/algorithms/search`, { params: { user_name: user_name } }).then((res) => {
    studiedAlgList.value = res.data;
    if (studiedAlgList.value.length > 0) {
      haveStudy.value = true;
    }
  })
}
// 标签数组
const tagList = ref([
  "info", "primary", "success", "warning", "danger"
])

// 收藏题集
let haveConllect = ref(false);
const collectionList = ref([]);
const findData = ref({
  alg_id: "",
  sequnence: "",
  user_id: user.value.id,
})
// 获取用户收藏列表
const getCollectinList = async () => {
  await axios.put(`/oasadapi/collect`, findData.value).then((res) => {
    // console.log(res.data);
    collectionList.value = res.data;
    collectionList.value.forEach(item => {
      item.exercise.content = item.exercise.content.split('.')[1]
    })
    if (res.data.length > 0) { haveConllect.value = true; }
    else { haveConllect.value = false; }
  })
}
// 加载图片
const getImageUrl = (url: string) => {
  // 里面可以根据需求写逻辑
  return new URL('../../assets/' + url, import.meta.url).href;
};
// 取消收藏
const cancel = async (id: number) => {
  await axios.delete(`/oasadapi/collect/${id}`).then((res) => {
    if (res.data.code === 0) {
      ElMessage.success('已取消收藏');
      getCollectinList();
    } else {
      ElMessage.error('取消失败！请检查网络');
    }
  })
}

// 我的评论
let haveComment = ref(false);
// 获取评论列表
const commentList = ref([{
  is_published: 0,
  author_id: 0,
  avatar: "",
  user: {
    user_avatar: "",
  },
}]);
const getCommentList = async () => {
  const res = await axios.get("/oasadapi/comment");
  commentList.value = res.data;
  if (commentList.value.length > 0)
    commentList.value = commentList.value.filter((item) => item.is_published == 1 && item.author_id === user.value.id);
  if (commentList.value.length > 0) {
    haveComment.value = true;
    commentList.value.forEach(item => {
      item.avatar = item.user.user_avatar;
    })
  }
  else { haveComment.value = false }
}
// 发送消息结构体
const notice = ref({
  notice: "",
  user_name: "",
  user_id: "",
  post_time: "",
  post_from: user.value.user_name,
})
// 撤回评论
const approvalData = ref({
  id: "",
  status: "",
})
const handleApproval = async (data, approvalStatus) => {
  approvalData.value.id = data.id;
  approvalData.value.status = approvalStatus;
  await axios.post(`/oasadapi/comment/approval`, approvalData.value).then((res) => {
    if (res.data.code === 0) {
      notice.value.notice = "您成功撤回一条评论！"
      ElMessage({
        message: "已撤回评论！",
        type: "success"
      })
      notice.value.user_name = data.author;
      axios.post(`/oasadapi/notice`, notice.value);
    } else {
      ElMessage({
        message: "撤回失败！",
        type: "error"
      })
    }
    getCommentList();
  })
}

// 我的消息
let haveLike = ref(false);
const activeNames = ref(0);
// 获取用户消息列表
const noticeList = ref([]);
const notRead = ref(0);
const getNoticeList = async (user_name: string) => {
  await axios.get(`/oasadapi/notice`, { params: { user_name: user_name } }).then((res) => {
    noticeList.value = res.data;
    if (noticeList.value.length > 0) {
      haveLike.value = true;
      activeNames.value = noticeList.value[0].id;
      noticeList.value.forEach(item => {
        if (item.status === 0) {
          notRead.value = notRead.value + 1;
        }
      })

    }
  })
}
// 修改为已读
const approval = ref({
  id: "",
  status: 1,
})
const handleChangeStatus = async (data) => {
  if (data.status === 1) { return }
  else {
    approval.value.id = data.id;
    approval.value.status = 1;
    await axios.post(`/oasadapi/notice/changestatus`, approval.value).then(() => {
      axios.get(`/oasadapi/notice`, { params: { user_name: user.value.user_name } }).then((res) => {
        noticeList.value = res.data;
        notRead.value = 0;
        noticeList.value.forEach(item => {
          if (item.status === 0) {
            notRead.value = notRead.value + 1;
          }
        })
        activeNames.value = data.id;
      });

    });
  }
}

//登出
// 注销按钮事件
const { changeRouter } = useRouterStore();
const handleLogout = async (id: number) => {
  dialogLogoutVisible.value = false;
  await axios.delete(`/oasadapi/users/${id}`).then(() => {
    userStore.changeUser({});
    changeRouter(false);
    router.push("/home");
    ElMessage({
      message: "注销成功！",
      type: "success"
    })
  })
}
</script>

<style lang="scss" scoped>
.user-avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  margin: auto;

  img {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    border: 1px solid #111;
  }
}

.center-items {
  margin-top: 15px;

  .el-row {
    margin-bottom: 20px;
  }

  .el-row:last-child {
    margin-bottom: 0;
  }

  .el-col {
    border-radius: 4px;
    margin: auto;
  }

  .grid-content {
    background: linear-gradient(#5a6bea, #1de9ed);
    border-radius: 4px;
    height: 56px;
    margin-left: 2px;
    margin-right: 2px;
    text-align: center;
    line-height: 56px;
    cursor: pointer;
    transition: all 0.2s linear;
  }

  .grid-content:hover {
    transform: scale(1.1);
    box-shadow: 3px 3px 4px #ccc;
  }
}

.info-item {
  display: flex;
  margin-bottom: 20px;
  font-size: 20px;
  width: 400px;
  margin: auto;

  .icon {
    width: 20px;
    height: 20px;
    margin-right: 7px;
    margin-top: 2px;

    img {
      width: 20px;
      height: 20px;
    }
  }
}

.study {
  margin: auto;

  .study-items {
    margin-right: 10px;
    cursor: pointer;
  }
}

.collection {
  .pic {
    width: 250px;

    img {
      width: 100%;
    }
  }
}

.logout-text {
  margin-left: 36%;
  font-size: 20px;
}

.notice {
  border-top: 0.5px solid #ccc;
}

.comment-top {
  border-bottom: 1px solid #ccc;
  margin-bottom: 5px;
}


.comment-card {
  width: 98%;
  display: flex;
  position: relative;
  border: 1px solid #ccc;
  border-radius: 10px;
  margin-bottom: 5px;
  padding: 5px;

  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-left: 10px;
    margin-right: 20px;

    img {
      width: 50px;
      height: 50px;
      border-radius: 50%;
    }
  }

  .comment-rigth {

    .userName {
      margin-bottom: 5px;
      color: #ccc;
    }

    .comment-text {
      margin-bottom: 5px;
    }

    .comment-time {
      margin-top: 10px;
      color: #ccc;
    }
  }

  .withdraw {
    margin-top: 25px;
    margin-left: 180px;
  }
}

// 头像
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}
</style>